#include "stdafx.h"
#include "ZNetworkSendBuffer.h"
#include "ZStream.h"
#include "ZUtility.h"

namespace	Z	{

//------------------------------------------------------------------------------------------------------------------------
NetworkSendBuffer::NetworkSendBuffer()
{
}

NetworkSendBuffer::~NetworkSendBuffer()
{
}

size_t NetworkSendBuffer::getWsaBufCount()	const
{
	size_t kWsaBufCount	= 0;
	for(Streams::const_iterator i = mStreams.begin(); i != mStreams.end(); ++i)	{
		if((*i)->getReadableSize() == 0)
			return kWsaBufCount;
		++kWsaBufCount;
	}
	return mStreams.size();
}

void NetworkSendBuffer::getWsaBufs(WSABUF* kWsaBufs, size_t kWsaBufCount)	const
{
	assert(kWsaBufCount <= getWsaBufCount());

	Streams::const_iterator last	= mStreams.begin();
	std::advance(last, kWsaBufCount);
	size_t w	= 0;
	for(Streams::const_iterator i = mStreams.begin(); i != last; ++i)	{
		kWsaBufs[w].buf	= (char*)(*i)->getReadableBuffer();
		kWsaBufs[w++].len	= (*i)->getReadableSize();
	}
}

void NetworkSendBuffer::onComplete(size_t bytesTransferred)
{
	size_t transferred	= bytesTransferred;
	while(0 < transferred)	{
		Stream* pStream	= mStreams.front();
		const size_t readableSize	= std::min<size_t>(pStream->getReadableSize(), transferred);
		assert(0 < readableSize);
		pStream->onRead(readableSize);
		transferred	-= readableSize;
		//if(pStream->exhausted())	{
		//	mStreams.pop_front();
		//	pStream->recycle();
		//	mStreams.push_back(pStream);
		//}
		if(pStream->getReadableSize() == 0)	{
			mStreams.pop_front();
			deletePtr(pStream);
		}
	}
}

}